package com.szy.assembly;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;

public class Peripheral implements Serializable {
    //public ArrayList<Integer> registerAddress;

    public HashMap<Integer,Integer> registers;

    public transient IOChangedNotifier ioChangedNotifier;
    public transient InterruptRequest interruptRequest;

    public int base;

    public static int getBits(int origin,int lowBitIndex,int bitNum){
        return (origin>>lowBitIndex)&((1<<(bitNum))-1);
    }


    public int getRegisterBits(int address, int lowBitIndex,int bitNum){
        return (registers.getOrDefault(address,0)>>lowBitIndex)&((1<<(bitNum))-1);
    }
    public void setRegisterBits(int address, int lowBitIndex,int bitNum,int value){
        int origin=registers.getOrDefault(address,0);
        int mask=((1<<(bitNum))-1) << lowBitIndex;
        origin &= ~mask;
        origin |= (value << lowBitIndex) & mask;
        registers.put(address,origin);
    }
    public Peripheral(int baseAddress){
        base=baseAddress;
    }

    public Peripheral setIoChangedNotifier(IOChangedNotifier ioChangedNotifier) {
        this.ioChangedNotifier = ioChangedNotifier;
        return this;
    }
    public Peripheral setInterruptRequester(InterruptRequest i){
        this.interruptRequest=i;
        return this;
    }
    //    public boolean isValidRegister(int address){
//        return registerAddress.contains(address);
//    }

    public boolean setRegister(int address,int value){
        if(registers.containsKey(address)){
            registers.put(address,value);
            return true;
        }else{
            return false;
        }
    }

    public int[] getRegister(int address){
        int[] res=new int[2];
        if(registers.containsKey(address)){
            res[0]=1;
            res[1]=registers.get(address);
        }
        return res;
    }

    public void ioChangedByHardware(int ioNumber, int value){

    }

    public void tickTask(){

    }


}
